<template>
    <div>
        <el-button type="primary" style="margin-bottom: 10px;" size="medium" @click="handleAddVisible">新增</el-button>
        <el-table :data="GPXData" border :header-cell-style="headerStyleEvent">
            <el-table-column prop="materialCategoryName" label="所属种类" align="center"></el-table-column>
            <el-table-column prop="materialTypeSpecification" width="120px" label="所属类型/规格"
                align="center"></el-table-column>
            <el-table-column prop="materialSerialNo" width="140px" label="物品序列号" align="center"></el-table-column>
            <el-table-column prop="materialDesc" width="120px" label="物品说明" align="center"></el-table-column>
            <el-table-column prop="qty" label="数量" align="center"></el-table-column>
            <el-table-column prop="unitType" label="单位" align="center"></el-table-column>
            <el-table-column prop="usedQtyValue" width="110px" label="当前使用值" align="center"></el-table-column>
            <el-table-column prop="thresholdManageValue" label="使用阈值" align="center"></el-table-column>
            <el-table-column prop="maxManageValue" width="110px" label="使用最大值" align="center"></el-table-column>
            <el-table-column prop="thresholdManageType" width="110px" label="阈值管理方式" align="center"></el-table-column>
            <el-table-column prop="lastMaintainTimeStr" width="140px" label="上次维护使用时间" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="180px">
                <template slot-scope="scope">
                    <div v-if="$store.state.theme.useCustomTheme === ''">
                        <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="text" @click="handleReset(scope.row)">重置使用值</el-button>
                    </div>
                    <div v-else>
                        <el-button size="mini" style="color: #409eff;" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" style="color: #409eff;" @click="handleReset(scope.row)">重置使用值</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <pagination :page.sync="searchParams.page" :limit.sync="searchParams.limit" :total="total"
            @pagination="getGPXdata">
        </pagination>
        <!-- 新增编辑 -->
        <el-dialog :title="isEdit ? '修改GPX物品' : '新增GPX物品'" :visible.sync="dialogVisible" width="50%">
            <el-form ref="form" :model="formmodel" label-width="160px" :rules="rules">
                <el-form-item label="物品种类" prop="materialCategoryId">
                    <commonSelect v-model="formmodel.materialCategoryId" style="width: 100%;" :list="categoryList"
                        :placeholder="'请选择种类'" @change="materialCategoryIdChanged">
                    </commonSelect>
                    <el-tag type="warning" style="white-space:break-spaces;height:auto;line-height:1.5em;">
                        [可不选 - 如果不存在要选择的种类，请先在“物品种类”中添加]
                    </el-tag>
                </el-form-item>
                <el-form-item label="物品类型/规格" prop="materialTypeId">
                    <commonSelect v-model="formmodel.materialTypeId" style="width: 100%;" :list="TypeList"
                        :placeholder="'请选择类型/规格'">
                    </commonSelect>
                    <el-tag type="warning" style="white-space:break-spaces;height:auto;line-height:1.5em;">
                        [可不选 - 如果不存在要选择的类型/规格，请先在“物品类型/规格”中添加]
                    </el-tag>
                </el-form-item>
                <el-form-item label="物品序列号/具体名称" prop="materialSerialNo">
                    <el-input v-model="formmodel.materialSerialNo"></el-input>
                </el-form-item>
                <el-form-item label="数量" prop="qty">
                    <el-input-number v-model="formmodel.qty" controls-position="right" :min="1"></el-input-number>
                    <span style="margin-left: 20px;">通常为一个</span>
                </el-form-item>
                <el-form-item label="数量单位" prop="unitType">
                    <commonSelect v-model="formmodel.unitType" style="width: 100%;" :list="unitTypeList"
                        :placeholder="'请选择数量单位'">
                    </commonSelect>
                </el-form-item>
                <el-form-item label="当前使用值" prop="usedQtyValue">
                    <el-input v-model="formmodel.usedQtyValue"></el-input>
                    <el-tag type="warning" style="white-space:break-spaces;height:auto;line-height:1.5em;">
                        指的是物品的使用次数、使用时间或百分比，按不同种类表示不同的使用单位
                    </el-tag>
                    <el-tag v-if="isEdit" type="error" style="white-space:break-spaces;height:auto;line-height:1.5em;">
                        [通常不应该手动修改使用值！！！]
                    </el-tag>
                </el-form-item>
                <el-form-item label="物品说明" prop="materialDesc">
                    <el-input v-model="formmodel.materialDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="isEdit ? handleUpdate() : handleAdd()">确
                    定</el-button>
            </span>
        </el-dialog>
        <!-- 重置使用值 -->
        <el-dialog title="物品使用值管理登记" :visible.sync="resetDialogVisible" width="45%">
            <p style="margin-bottom: 16px;text-align: center;">管理物品使用次数/时间等的重置(通常用于维护后重新统计使用值)</p>
            <el-form ref="formReset" :model="formmodelReset" label-width="160px" :rules="resetrules">
                <el-form-item label="物品序列号/具体名称" prop="materialSerialNo">
                    <el-input v-model="formmodelReset.materialSerialNo" disabled></el-input>
                </el-form-item>
                <el-form-item label="当前使用值" prop="usedQtyValue">
                    <el-input v-model="formmodelReset.usedQtyValue" disabled></el-input>
                </el-form-item>
                <el-form-item label="维护时间" prop="maintainTimeStr">
                    <el-date-picker v-model="formmodelReset.maintainTimeStr" type="date" placeholder="选择日期">
                        <p>默认今天</p>
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="维护人" prop="maintainUser">
                    <el-input v-model="formmodelReset.maintainUser"></el-input>
                </el-form-item>
                <el-form-item label="维护人工号" prop="maintainEmpNo">
                    <el-input v-model="formmodelReset.maintainEmpNo"></el-input>
                </el-form-item>
                <el-form-item label="维护说明" prop="maintainMark">
                    <el-input v-model="formmodelReset.maintainMark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleResetMaterial">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import Pagination from '@/components/Pagination.vue';
import commonSelect from '@/components/commonSelect.vue';
import dayjs from 'dayjs';
import { setMaterielCTCategory, fetchGoodTypeSelect, fetchGoodCategorySelect } from '@/network/MaterialCategoryType';
import { setMaterielSDUCategory, fetchMaterial, fetchUpdeteMaterial, fetchAddMaterial, fetchResetMaterial } from '@/network/MaterialSpecificDetailUse';
export default {
    name: '',
    props: {},
    components: {
        Pagination,
        commonSelect
    },
    data() {
        return {
            GPXData: [],
            total: 0,
            searchParams: {
                limit: 10,
                page: 1,
            },
            categoryList: [],
            TypeOriginList: [],
            unitTypeList: [{
                id: '个',
                name: '个'
            }, {
                id: '盒',
                name: '盒'
            },
            {
                id: '套',
                name: '套'
            }],
            isEdit: false,
            dialogVisible: false,
            resetDialogVisible: false,
            rules: {
                // [对于特定的commonSelect组件]规则中必须显式指定required: false 或者 不指定任何 才取消必需条件
                // materialCategoryId: [{ required: false, message: '请选择种类', trigger: 'change' }],
                // materialTypeId: [{  message: '请选择型号', trigger: 'change' }],
                materialSerialNo: [{ required: true, message: '请输入物品序列号', trigger: 'blur' }],
                materialDesc: [{ message: '请输入描述', trigger: 'blur' }],
                qty: [{ required: true, message: '请输入数量', trigger: 'blur' }],
                unitType: [{ required: true, message: '请选择数量单位', trigger: 'change' }],
                usedQtyValue: [{ required: true, message: '请输入当前使用值', trigger: 'blur' }],
            },
            resetrules: {
                maintainEmpNo: [{ required: true, message: '请输入维护人工号', trigger: 'blur' }],
                maintainTimeStr: [{ required: true, message: '请选择维护时间', trigger: 'change' }],
                maintainUser: [{ required: true, message: '请输入维护人', trigger: 'blur' }],
                maintainMark: [{ required: true, message: '请输入说明', trigger: 'blur' }],
            },
            formmodel: {
                materialCategoryId: null,//所属种类Id
                materialTypeId: null,//所属类型/规格Id
                materialSerialNo: '',//物品序列号/具体名称
                materialDesc: '',//物品的描述说明
                qty: 1,//单个物品
                unitType: '',//数量单位
                usedQtyValue: ''//当前使用值
            },
            formmodelReset: {
                materialId: '',
                materialSerialNo: '',
                usedQtyValue: '',
                maintainTimeStr: dayjs().format('YYYY-MM-DD'),
                maintainUser: '',
                maintainMark: '',
                maintainEmpNo: ''
            }
        }
    },
    computed: {
        TypeList() {
            return this.TypeOriginList.filter(l =>
                l.categoryId === this.formmodel.materialCategoryId
            ).map(l => ({
                id: l.typeId,
                name: l.typeName,
            }));
        }
    },
    mounted() {
        setMaterielCTCategory(this.$route.meta.materielCTCategory)
        setMaterielSDUCategory(this.$route.meta.materielSDUCategory)

        this.getGPXdata()
        this.getCategorySelect()
        this.getTypeSelect()
    },
    methods: {
        headerStyleEvent() {
            if (this.$store.state.theme.useCustomTheme === "7-gpx") {
                return { background: '#f5f5f5', color: '#2F4F4F' };
            } else {
                return { background: '#eef1f6', color: '#606266' }
            }
        },
        materialCategoryIdChanged() {
            this.formmodel.materialTypeId = null;
        },
        async getGPXdata() {
            try {
                const res = await fetchMaterial(this.searchParams)
                this.GPXData = res.data
                this.searchParams.page = res.page
                this.searchParams.limit = res.limit
                this.total = res.total
                console.log(res);

            } catch (error) {
                console.log(error);
            }
        },
        async getCategorySelect() {
            try {
                const res = await fetchGoodCategorySelect()
                this.categoryList = res.data.map(item => ({
                    id: item.id,
                    name: item.categoryName,
                }));
            } catch (error) {
                console.log(error);
            }
        },
        async getTypeSelect() {
            try {
                const res = await fetchGoodTypeSelect()
                this.TypeOriginList = res.data.map(item => ({
                    categoryId: item.materialCategoryId,
                    categoryName: item.materialCategoryName,
                    typeId: item.id,
                    typeName: item.typeSpecification,
                }));
            } catch (error) {
                console.log(error);
            }
        },
        async handleUpdate() {
            try {
                const valid = await this.$refs['form'].validate().catch(err => false);
                if (valid) {
                    // 表单验证通过，执行新增线体请求
                    const res = await fetchUpdeteMaterial(this.formmodel); // 确保使用的是 addForm 而不是 this.form
                    console.log(res);
                    // 新增成功后的提示
                    if (res.status == 200) {
                        this.$message({
                            message: '编辑成功',
                            type: 'success'
                        });
                        // 关闭对话框并重置表单
                        this.dialogVisible = false;
                        this.getGPXdata()
                        this.$refs['form'].resetFields(); // 重置表单
                    }
                }
            } catch (error) {
                // 捕获异常并输出错误
                console.error('编辑失败:', error);
            }
        },
        async handleAdd() {
            try {
                // 等待表单验证结果
                const valid = await this.$refs['form'].validate().catch(err => false);
                if (valid) {
                    // 表单验证通过，执行新增线体请求
                    const res = await fetchAddMaterial(this.formmodel); // 确保使用的是 addForm 而不是 this.form
                    console.log(res);
                    // 新增成功后的提示
                    if (res.status == 200) {
                        this.$message({
                            message: '新增成功',
                            type: 'success'
                        });
                        // 关闭对话框并重置表单
                        this.dialogVisible = false;
                        this.getGPXdata()
                        this.$refs['form'].resetFields(); // 重置表单
                    }
                }
            } catch (error) {
                // 捕获异常并输出错误
                console.error('新增失败:', error);
            }
        },
        handleAddVisible() {
            this.dialogVisible = true
            this.isEdit = false
            this.formmodel = {
                materialCategoryId: null,//所属种类Id
                materialTypeId: null,//所属类型/规格Id
                materialSerialNo: '',//物品序列号/具体名称
                materialDesc: '',//物品的描述说明
                qty: 1,//单个物品
                unitType: '',//数量单位
                usedQtyValue: 0//当前使用值
            }
        },
        handleEdit(row) {
            const { id, materialCategoryId, materialTypeId, materialSerialNo, materialDesc, qty, unitType, usedQtyValue } = row;
            this.formmodel = {
                id,
                materialCategoryId,
                materialTypeId,
                materialSerialNo,
                materialDesc,
                qty,
                unitType,
                usedQtyValue
            };
            this.isEdit = true
            this.dialogVisible = true
        },
        handleReset(row) {
            this.formmodelReset.materialId = row.id
            this.formmodelReset.usedQtyValue = row.usedQtyValue
            this.formmodelReset.materialSerialNo = row.materialSerialNo

            this.formmodelReset.maintainUser = ''
            this.formmodelReset.maintainEmpNo = ''
            this.formmodelReset.maintainMark = ''

            this.resetDialogVisible = true
        },
        handleResetMaterial() {
            this.$refs['formReset'].validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await fetchResetMaterial(this.formmodelReset)
                        this.resetDialogVisible = false
                        if (res.status == 200) {
                            this.$message({
                                message: '重置成功',
                                type: 'success'
                            });
                            this.getGPXdata()
                            this.$refs['formReset'].resetFields();
                        }
                    } catch (error) {
                        console.log(error);
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    }
}

</script>
<style>
.el-form-item {
    margin-bottom: 16px;
}

div.el-form-item__content {
    line-height: normal;
}
</style>